//
//  WebViewController.m
//  NC-Trendy
//
//  Created by LeungChaos on 16/2/24.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "WebViewController.h"

@interface WebViewController ()

@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, assign) CGRect webFrame;

@property (nonatomic, weak) UIWebView *webView;

@end

@implementation WebViewController

- (UIWebView *)webView {
    if (_webView == nil) {
        UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH + kTabBarH)];
        webView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:webView];
        _webView = webView;
    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self webView];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hud show:YES];
    
    if (self.artcle_id) {
        NCArticle *article = [self loadArtiCleInCoreDB];
        if (article) {
            [self loadHtmlWithArticle:article];
            [self.hud hide:YES];
        } else {
            [self showArticle];
        }
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.hud hide:YES];
        });
    }
    // Do any additional setup after loading the view.
}

//读取本地数据库
- (NCArticle *)loadArtiCleInCoreDB {
    CoreArticle *cArticle = [ArticleDBTools selectCoreArticleWithID:self.artcle_id errorInfo:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    if (cArticle) {
        return [ArticleDBTools ncArticleWithCoreArticle:cArticle];
    } else {
        return nil;
    }
}

- (void)showArticle {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlPath = [NSString stringWithFormat:@"%@/%@/%@",Localhost,Article,aSelectArticle];
   // NSDictionary *dic = @{@"article_id":self.artcle_id};
    NSDictionary *dic = @{@"a_id":self.artcle_id};
    NSLog(@"dic %@?%@",urlPath,dic);
    [manager GET:urlPath parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",[responseObject class]);
        NSLog(@"%@",responseObject);

        if ([responseObject isKindOfClass:[NSData class]]) {
            NSError *error;
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
            NSLog(@"json dic %@",jsonDict);
            if (!error) {
                if ([jsonDict[@"status"] isEqualToString:@"1"]) {
                    NSDictionary *dic = [jsonDict[@"data"]lastObject];
                    NCArticle *article = [[NCArticle alloc]initWithDic:dic];
                    [ArticleDBTools insertCoreArticleWithArticle:article errorInfo:^(NSError *error) {
                        NSLog(@"%@",error);
                    }];
                    [self loadHtmlWithArticle:article];
                }
            } else {
                NSLog(@"%@",error);
            }
            
        }
            [self.hud hide:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [self.hud hide:YES];
    }];

}
#pragma mark 解析html
- (void)loadHtmlWithArticle:(NCArticle *)article {
    //时间
    NSString *timeStr = article.article_addtime;
    //作者
    NSString *author = article.article_author;
    //标题
    NSString *title = article.article_title;
    //内容
    NSString *content = article.article_content;
    //解析 时间戳
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"yyyy年MM月dd日"];
    NSTimeInterval scd = [timeStr doubleValue];
    NSString *addtime = [dateFormat stringFromDate:[NSDate dateWithTimeIntervalSince1970:scd]];
    //拼表头
    NSString *header = [NSString stringWithFormat:@"<meta charset=\"UTF-8\"><div class=\"title\">%@</div><p></p><div class=\"author\">作者:%@</div><div class=\"time\">%@</div>", title, author, addtime];
    //拼css文件路径
    NSURL *cssURL = [[NSBundle mainBundle] URLForResource:@"news" withExtension:@"css"];
    // NSString *css = [NSString stringWithFormat:@"%@<link rel=\"stylesheet\" href=\"%@\">", html, cssURL];
    //拼成整篇文章
    NSString *htmlStr = [NSString stringWithFormat:@"%@%@<link rel=\"stylesheet\" href=\"%@\">",header,content,cssURL];
    //webView加载文章
    [self.webView loadHTMLString:htmlStr baseURL:nil];
}

//页面要出现时隐藏tabBar
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    NSLog(@"NO %@",NSStringFromCGRect(self.view.frame));
    RootTabBarViewController *rootViewContro = (RootTabBarViewController *)[AppDelegate shareAppDelegate].window.rootViewController;
    rootViewContro.isHide = NO;
}

//页面要消失时显示tabBar
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    RootTabBarViewController *rootViewContro = (RootTabBarViewController *)[AppDelegate shareAppDelegate].window.rootViewController;
    rootViewContro.isHide = YES;
//    NSLog(@"%@",NSStringFromCGRect(self.view.frame));
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
